<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						size="small"
						class="item-gap"
						@click="onExportExcel"
					>导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<div class="search-bar-item-size2 item-gap">
						<el-date-picker v-model="searchParams.yearMonth" :clearable="false" size="small" style="width: 100%;" type="month" value-format="yyyy-MM" placeholder="月" />
					</div>
					<!--<jk-search-input v-model="searchParams.productionLineNameOrCode" @on-enter="onSearchBtn" :clearable="false" placeholder="产线编号或名称" class="search-bar-item-size2 margin-5-0 item-gap"></jk-search-input>-->
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				show-footer
				:loading="tableLoading"
				:span-method="mergeColMethod"
				:footer-method="footerMethod"
				border
				:stripe="false"
				:data="tableData"
				:height="tableHeight + 30"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.value"
					:align="item.align"
					:field="item.key"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.key === 'code'">{{ scope.row.code }}</span>
						<span v-else>{{ scope.row[item.key] }}</span>
					</template>
				</vxe-column>
			</jk-table>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { reportFrontSpinningMbMonthData } from '../../../api/production/frontGroupYieldStatistics';
    import { exportExcelMerge } from '../../../api/commont';
    import XEUtils from 'xe-utils';
    export default {
        name: 'MbMonthReport',
        components: {},
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': reportFrontSpinningMbMonthData
                },
                totalData: {
                    totalOutputM: 0,
                    totalOutputKg: 0
                },

                processList: [],
                tableData: [],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                count: 0,
                searchParams: {
                    yearMonth: '',
                    workshopId: null
                }
            };
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.$set(this.searchParams, 'workshopId', this.workshopList.find(x => x.name === '前纺区域') ? this.workshopList.find(x => x.name === '前纺区域').id : this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.getDependentData();
        },
        methods: {
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                if (params.yearMonth) {
                    params.year = new Date(params.yearMonth).getFullYear();
                    params.month = new Date(params.yearMonth).getMonth() + 1;
                }
                this.apiItem.page(params).then(res => {
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = this.tableColumnList.map(x => x.value);
                            const filterVal = this.tableColumnList.map(x => x.key);
                            const list = res.data.res.tableData ? res.data.res.tableData : [];
                            // 合计项
                            const totalItem = {};
                            this.tableColumnList.forEach(headItem => {
                                if (!totalItem[headItem.key]) {
                                    totalItem[headItem.key] = 0;
                                }
                                if (headItem.key === 'belongDate') {
                                    totalItem[headItem.key] = `合计: ${this.totalData.totalOutputM || 0}M; ${this.totalData.totalOutputKg || 0}KG`;
                                } else {
                                    list.forEach(rowItem => {
                                        totalItem[headItem.key] = totalItem[headItem.key] + (rowItem[headItem.key] || 0);
                                    });
                                }
                            });
                            list.push(totalItem);
                            const data = this.formatJson(filterVal, list);
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                    this.exportLoading = false;
                });
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `合计: ${this.totalData.totalOutputM || 0}M; ${this.totalData.totalOutputKg || 0}KG`;
                        }
                        if (column.property !== 'belongDate') {
                            // if (column.property.indexOf('Kg') !== -1) {
                            //     return XEUtils.sum(data, column.property) + 'KG';
                            // } else {
                            //     return XEUtils.sum(data, column.property) + 'M';
                            // }
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            onReportBtn() {
                const titleList = this.tableColumnList.map(x => x.title);
                const valueList = [];
                let rowArr = [];
                const cpData = this.tableData ? JSON.parse(JSON.stringify(this.tableData)) : [];
                cpData.forEach(d => {
                    rowArr = [];
                    this.tableColumnList.forEach(h => {
                        rowArr.push(d[h.key]);
                    });
                    valueList.push(rowArr);
                });
                const fileName = `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`;
                if (cpData.length) {
                    exportExcelMerge({
                        titleList,
                        valueList,
                        mergedKey: '',
                        fileName: fileName
                    }).then(res => {
                        if (res.data.status === 200) {
                            const href = 'http://spin.jeacon.cn/excel' + res.data.res.path;
                            const downA = document.createElement('a');
                            downA.href = href;
                            downA.click();
                            // 销毁超连接
                            window.URL.revokeObjectURL(href);
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '当前没有数据可以导出!');
                }
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'belongDate') {
                    if (prevRow && prevRow.belongDate === row.belongDate) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.belongDate === row.belongDate) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                // await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId) {
                    this.tableLoading = true;
                    const params = { ...this.searchParams };
                    if (params.yearMonth) {
                        params.year = new Date(params.yearMonth).getFullYear();
                        params.month = new Date(params.yearMonth).getMonth() + 1;
                    }
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        this.count = res.data.count;
                        if (res.data.status === 200) {
                            this.tableColumnList = res.data.res.tableHeader ? res.data.res.tableHeader.map(x => {
                                if (x.key === 'belongDate') {
                                    x.width = 160;
                                    x.align = 'left';
                                } else {
                                    x.width = 140;
                                    x.align = 'right';
                                }
                                return x;
                            }) : [];
                            this.tableData = res.data.res.tableData ? res.data.res.tableData.map(x => {
                                return x;
                            }) : [];
                            this.totalData = res.data.res.total;
                        }
                    });
                }
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            }
        }
    };
</script>
<style>
    .machine-group-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        border-left: solid 1px #eee;
        border-top: solid 1px #eee;
        width: 80px;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 0 4px;
        flex-shrink: 0;
    }
</style>
